package com.anxin.act.task.service;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anxin.act.model.service.WfActApproverService;
import com.anxin.act.task.entity.ViewHiTask;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActProcessUtils;
import com.anxin.act.utils.ActTaskUtils;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.DateUtils;
import com.anxin.common.utils.ListUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.redis.MqProducer;
import com.anxin.framework.redis.RedisMq;
import com.anxin.sys.message.utils.SendMessageUtils;
import com.anxin.sys.system.entity.SysUser;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 流程抄送
 */
@Service
public class ActSendCcService implements RedisMq {
    @Autowired
    private HistoryService historyService;
    @Autowired
    private WfActApproverService wfActApproverService;
    @Autowired
    private MqProducer mqProducer;
    @Autowired
    private WfCcRecordService wfCcRecordService;
    @Autowired
    private ViewHiTaskService viewHiTaskService;

    /**
     * 发送抄送
     * @param taskVo
     */
    public void sendCc(TaskVo taskVo,String id){
        JSONObject messageJson = new JSONObject();
        messageJson.put("taskId",taskVo.getTaskId());
        messageJson.put("id",id);
        messageJson.put("ccUserArray",taskVo.getCcUser());

        // 默认发送抄送信息
        mqProducer.sendMessage(ActSendCcService.class,messageJson.toJSONString());
    }

    /**
     * 发送抄送
     * @param taskId
     */
    public void sendCc(String taskId){
        JSONObject messageJson = new JSONObject();
        messageJson.put("taskId",taskId);
        messageJson.put("ccUserArray",new JSONArray().toJSONString());

        // 默认发送抄送信息
        mqProducer.sendMessage(ActSendCcService.class,messageJson.toJSONString());
    }

    /**
     * 发送抄送
     * @param id 任务ID
     * @param taskId 任务对应的Activity任务ID
     */
    public void sendCc(String id,String taskId){
        JSONObject messageJson = new JSONObject();
        messageJson.put("taskId",taskId);
        messageJson.put("id",id);
        messageJson.put("ccUserArray",new JSONArray().toJSONString());

        // 默认发送抄送信息
        mqProducer.sendMessage(ActSendCcService.class,messageJson.toJSONString());
    }

    /**
     * 根据待办ID发送抄送信息
     * @param historicTaskInstance
     */
    public List<String> getCcUser(HistoricTaskInstance historicTaskInstance){
        List<String> resUserIdList = new ArrayList<>();

        ActivityImpl activityImpl = ActUtils.getActivityImpl(historicTaskInstance.getProcessDefinitionId(), historicTaskInstance.getTaskDefinitionKey());
        String ccusers = activityImpl.getProperty("ccusers") != null ? activityImpl.getProperty("ccusers").toString() : "";
        if (StringUtils.isNotBlank(ccusers)){
            Map<String, Object> processVar = ActUtils.getProcessVar(historicTaskInstance.getProcessInstanceId());
            processVar.put("actId",historicTaskInstance.getProcessInstanceId());
            List<String> userNameList = wfActApproverService.getApprover(ccusers, "", null,processVar,null);
            resUserIdList = UserUtils.userNameToId(userNameList);
        }

        return resUserIdList;

    }


    /**
     * 发送抄送
     * @param message
     * @return
     */
    @Override
    public boolean onMessage(String message) {
        JSONObject json = JSONObject.parseObject(message);
        // 任务ID
        String id = StringUtils.isNotBlank(json.getString("id")) ? json.getString("id") : json.getString("taskId");
        // 任务对应的Activity任务ID
        String taskId = json.getString("taskId");

        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).includeTaskLocalVariables().singleResult();

        ViewHiTask viewHiTask = viewHiTaskService.get(id);

        // 获取节点默认配置的发送人
        List<String> ccUserList = this.getCcUser(historicTaskInstance);

        //List中加入手动抄送的用户
        JSONArray ccUserArray = json.getJSONArray("ccUserArray");
        ListUtils.copyList(ccUserArray,ccUserList);

        if (ccUserList.size() > 0){
            JSONObject messageJson = new JSONObject();
            // 审批人
            String userName = viewHiTask.getAssignee() != null ? viewHiTask.getAssignee() : "";
            messageJson.put("approve","");
            if (StringUtils.isNotBlank(userName)){
                SysUser sysUser = UserUtils.getUserByUserName(userName);
                if (sysUser != null){
                    messageJson.put("approve",sysUser.getNickName());
                }
            }

            // 申请人
            String applicantUserName = ActProcessUtils.getApplicant(historicTaskInstance.getProcessInstanceId());
            SysUser applicantUser = UserUtils.getUserByUserName(applicantUserName);
            messageJson.put("applicant",applicantUser != null ? applicantUser.getNickName() : "-");

            // 审批时间
            messageJson.put("approvalTime", DateUtils.format(viewHiTask.getApprovalTime()));
            // 待办标题
            messageJson.put("title",ActProcessUtils.getProcessTitle(historicTaskInstance.getProcessInstanceId()));
            // 审批意见
            messageJson.put("opinions", ActTaskUtils.getTaskComments(id));
            // 组件地址
            messageJson.put("component","@/views/act/process/processInfoForm");
            // 数据ID
            messageJson.put("dataId",historicTaskInstance.getProcessInstanceId());
            // 其他参数
            messageJson.put("parameters",id);

            // 消息发送人ID
//            if (applicantUser != null){
//                messageJson.put("sendUserId",applicantUser.getId());
//            }


            // 发送消息
            SendMessageUtils.sendMessage("ccTask", ccUserList,messageJson);



            // 保存抄送记录
            wfCcRecordService.save(historicTaskInstance.getProcessInstanceId(),id,ccUserList);
        }



        return false;
    }
}
